package com.globant.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.IntentService;
import android.content.Intent;

import com.globant.common.MyApplication;
import com.globant.dao.TweetDao;
import com.globant.domain.SearchResponse;
import com.globant.twittersearch.TwitterConnection;

public class PeriodicTwitterSearchService extends IntentService {

	private SearchResponse tweets;
	private Timer timer;
		
	public PeriodicTwitterSearchService() {
		super("Test");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		timer = new Timer("TweetCollectorTimer");
		timer.schedule(new TimerTask() { 
			public void run() {
				TwitterConnection connection = new TwitterConnection();
				
				MyApplication application = (MyApplication) getApplication();
				
				String criteria = application.getSearch();
				
				if(criteria.length() > 0 ) {
					SearchResponse tweetsAsync = connection.obtainJson(criteria);
					if(tweets == null || !tweetsAsync.getQuery().contains(tweets.getQuery())) {
						tweets = tweetsAsync;
					} else {
						tweets.getResults().addAll(tweetsAsync.getResults());
						tweets.setNextPage(tweetsAsync.getNextPage());
					}
					
					if(tweets != null) {
						
						TweetDao storage = new TweetDao(getApplication());
						storage.insert(tweets);
					}
		
				}
			}
		}, 100, 1000L);
		
	}
}
